package com.dz.lm.common.utils;

import com.google.common.collect.Maps;
import com.dz.lm.common.utils.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * PostToMap工具类
 * 
 * @author zhanghairong
 * @since 2019-05-28
 */
public class PostToMap {

	private static final Logger logger = LoggerFactory
			.getLogger(PostToMap.class);
	
	public static final String CHARSETUTF8 = "UTF-8";
    public static final String CHARSETGBK = "GBK";

	public static Map<String, Object> getMap(HttpServletRequest request) {
		Map<String, Object> accountJsonMap = null;
		/*
		 * String file1=""; file1=request.getParameter("file"); if(file1!=null){
		 * byte[] b= Base64Coder.decodeLines(file1); String
		 * filepath=request.getSession
		 * ().getServletContext().getRealPath("/files"); File file=new
		 * File(filepath); if(!file.exists()) file.mkdirs(); FileOutputStream
		 * fos=new
		 * FileOutputStream(file.getPath()+"/person_head"+(int)(Math.random
		 * ()*100)+".png"); System.out.println(file.getPath()); fos.write(b);
		 * fos.flush(); fos.close(); }
		 */
		try {
			InputStream is = request.getInputStream();
			String str = null;
			try {
				StringBuffer sb = new StringBuffer();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String s = "";
				while ((s = br.readLine()) != null) {
					sb.append(s);
				}
				str = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.debug("PostToMap==>>JsonParameters:" + str);
			accountJsonMap = new HashMap<String, Object>();
			if (str != null && !"".equals(str)) {
				accountJsonMap = JsonUtils.readValue(str);
			}

		} catch (Exception e) {

		}
		return accountJsonMap;
	}

	public static Map<String, Object> getMap(HttpServletRequest request,
			String strTemp) {
		Map<String, Object> accountJsonMap = null;
		try {
			InputStream is = request.getInputStream();
			String str = null;
			try {
				StringBuffer sb = new StringBuffer();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String s = "";
				while ((s = br.readLine()) != null) {
					sb.append(s);
				}
				str = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.debug("PostToMap==>>JsonParameters:" + str);
			if (str != null && !"".equals(str)) {
				accountJsonMap = JsonUtils.getParameter(str);
			} else {
				accountJsonMap = new HashMap<String, Object>();
			}

		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return accountJsonMap;
	}
	
	/** 
     * 获取 RUL格式 post参数 
     * @param request 
     * @param charset 
     * @return param 
     * @author zhanghairong
     */  
    public static Map<String, Object> getPostURLParam(HttpServletRequest request, String charset) { 
        if(null==charset) charset = CHARSETUTF8;
        logger.debug("===================PostToMap==getPostURLParam==================");
        Map<String, Object> urlMap = null;
        String urlStr = null;  
        try {  
            urlStr = getPostParam(request,charset);  
            
            logger.debug("===================PostToMap==getPostURLParam=====urlStr:"+urlStr);
            
            if (urlStr != null && !"".equals(urlStr)) {
                urlMap = urlParamToMap(urlStr);
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return urlMap;  
    } 
	
	/** 
     * 获取 RUL格式 post参数 
     * @param request 
     * @param charset 
     * @return param 
     * @author zhanghairong
     */  
    public static Map<String, Object> getAliPayURLParam(HttpServletRequest request, String charset) { 
        if(null==charset) charset = CHARSETUTF8;
        
        logger.debug("===================PostToMap==getAliPayURLParam==================");
        Map<String, Object> urlMap = Maps.newHashMap();
        String urlStr = null;  
        try {  
                Map<String,String[]> mapRequest= request.getParameterMap();
                 Iterator<String> keys = mapRequest.keySet().iterator(); 
                   while(keys.hasNext()) { 
                   String key = (String) keys.next(); 
                   String[] value=mapRequest.get(key); 
                   if(value!=null){
                       urlMap.put(key, value[0]);
                       logger.debug("===================PostToMap==getAliPayURLParam=====key:"+key+"=================value:"+value[0]);
                   }else{
                       urlMap.put(key,value); 
                       logger.debug("===================PostToMap==getAliPayURLParam=====key:"+key+"=================value:");
                   }
                } 
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return urlMap;  
    } 
    
    /** 
     * 获取 XML格式 post参数 
     * @param request 
     * @param charset 
     * @return param 
     * @author zhanghairong
     */  
    public static Map<String, Object> getPostXMLParam(HttpServletRequest request, String charset) {
        Map<String, Object> xmlMap = null;
        return xmlMap;  
    } 
    
    /** 
     * 获取post参数 
     * @param request 
     * @param charset 
     * @return param 
     * @author zhanghairong
     */  
    public static String getPostParam(HttpServletRequest request, String charset) { 
        if(null==charset) charset = CHARSETUTF8;
        
        String pageString = null;  
        InputStreamReader isr = null;  
        BufferedReader br = null;  
        StringBuffer sb = null; 
        InputStream is = null;
        try {  
            is = request.getInputStream();
            isr = new InputStreamReader(is, charset);  
            br = new BufferedReader(isr);  
            sb = new StringBuffer();  
            String line = null;  
            while ((line = br.readLine()) != null) {  
                sb.append(line + "\n");  
            }  
            pageString = sb.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if(br!=null){  
                    br.close();  
                }  
                if(isr!=null){  
                    isr.close();  
                }  
                if (is != null){  
                    is.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            sb = null;  
        }  
        return pageString;  
    } 

    /** 
     * 将url参数转换成map 
     * @param param aa=11&bb=22&cc=33 
     * @return 
     */  
    public static Map<String, Object> urlParamToMap(String param) {  
        Map<String, Object> map = new HashMap<String, Object>(0);  
        if (StringUtils.isBlank(param)) {  
            return map;  
        }  
        String[] params = param.split("&");  
        for (int i = 0; i < params.length; i++) {  
            String[] p = params[i].split("=");  
            if (p.length == 2) {  
                map.put(p[0], p[1]);  
            }  
        }  
        return map;  
    } 

}
